<?php

class Tools {
    /* select element
     * 
     * $id int :select name
     * $opArr array: option data array
     * $op0 string: default option text
     * $isTextValue  boolean: put $opArr key or value in option value, true is key
     * $opValue string: selected value
     * $change string: select javascript event or others
     * 
     * return  select element
     */

    public static function selectOptions($id, $opArr, $op0, $isTextValue, $opValue, $change = '') {
        $select = !empty($op0) ? '<option value="">' . $op0 . '</option>' : '';
        $i = 0;
        foreach ($opArr as $key => $value) {
            $i++;
            $selected = $opValue == $key ? 'selected="selected"' : '';
            $select .= '<option value="' . ($isTextValue ? $key : ($i)) . '" ' . $selected . '>' . $value . '</option>';
        }
        return '<select name="' . $id . '" id="' . $id . '" ' . $change . '>' . $select . '</select>';
    }

    public static function selectOptionsMultiple($id, $opArr, $op0, $isTextValue, $opValue, $change = '') {
        $select = !empty($op0) ? '<option value="">' . $op0 . '</option>' : '';
        $i = 0;
        $_temp = explode(",", $opValue);
        foreach ($opArr as $key => $value) {
            $i++;
            $selected = in_array($key, $_temp) ? 'selected="selected"' : '';
            $select .= '<option value="' . ($isTextValue ? $key : ($i)) . '" ' . $selected . '>' . $value . '</option>';
        }
        return '<select name="' . $id . '" id="' . $id . '" ' . $change . '>' . $select . '</select>';
    }

    /* select element
     * 
     * $id int :select name
     * $opArr array: option data array
     * $op0 string: default option text
     * $isTextValue  boolean: put $opArr key or value in option value, true is key
     * $opValue string: selected value
     * $change string: select javascript event or others
     * $start int: option start value
     * $end int: option end value
     * 
     * return  select element
     */

    public static function selectOptions2($id, $op0, $isTextValue, $opValue, $change = '', $start, $end) {
        $select = !empty($op0) ? '<option value="">' . $op0 . '</option>' : '';
        $i = 0;

        for ($key = $start; $key <= $end; $key++) {//$opArr as $key=>$value){
            $i++;
            $selected = $opValue == $key ? 'selected="selected"' : '';
            $item = $key < 10 ? "0" . $key : $key;
            $select .= '<option value="' . ($isTextValue ? $item : ($i + 1)) . '" ' . $selected . '>' . $item . '</option>';
        }
        return '<select name="' . $id . '" id="' . $id . '" ' . $change . '>' . $select . '</select>';
    }

    /* select element
     * 
     * $grade string : from Data:: $_grade
     * $start int: option start value
     * $end int:option end value
     * $id  string: name and id of element
     * $op0 string: default option text
     * $opValue string: selected value
     * $change string: select javascript event or others
     * 
     * return  select element
     */

    public static function selectOptionsByGrade($grade, $start, $end, $id, $op0, $opValue, $change = '') {
        $select = !empty($op0) ? '<option value="">' . $op0 . '</option>' : '';
        $i = 0;
        if (empty($end))
            $end = date('Y', time());
        for ($key = $start; $key <= $end; $key++) {
            $i++;
            $selected = $opValue == $key ? 'selected="selected"' : '';
            $data = Tools::getGrade($key, $grade);
            $select .= '<option value="' . $key . '" ' . $selected . '>' . $data . '</option>';
        }
        return '<select name="' . $id . '" id="' . $id . '" ' . $change . '>' . $select . '</select>';
    }

    public static function getGrade($year, $grade) {
        $num = $year - Data::$_grade[$grade] + 1;
        $num = Tools::getChineseNumber($num);
        $data = $year . '年（' . ($year - 1911) . '級，第' . $num . '屆）';
        return $data;
    }

    public static function getChineseNumber($money) {
        $chrtext = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        $chrunit = array("", "十", "百");
        for ($i = 0; $i < strlen($money); $i++) {
            if ($a_unit == null) {//偵測位數 
                $a_unit = strlen($money) - 1;
            }
            //取出阿拉伯數數字 
            $a = substr($money, $i, 1);
            if ($a != 0) {//阿拉伯轉中文 
                $out_string .= ($i == 0 && $a == 1 && $a_unit > 1) ? "" : $chrtext[$a];
                //抓單位
                if ($i < $a_unit) {
                    $out_string .= $chrunit[$a_unit - $i];
                }
            }
        }
        return $out_string;
    }

    /* radio element
     * 
     * $id int :radio name
     * $opArr array: option data array
     * $isTextValue  boolean: put $opArr key or value in option value, true is key
     * $opValue string: selected value
     * $change string: select javascript event or others
     * 
     * return  radio element
     */

    public static function radioList($id, $opArr, $isTextValue, $opValue, $change = '') {

        $i = 0;
        foreach ($opArr as $key => $value) {
            $i++;
            $checked = $opValue == $key ? 'checked="checked"' : '';
            $select .= '<input type="radio" name="' . $id . '"  value="' . ($isTextValue ? $key : ($i)) . '" ' . $change . ' ' . $checked . ' />&nbsp;'.$value.'&nbsp;&nbsp;';
        }
        return $select;
    }

    /* checkbox element
     * 
     * $id int :radio name
     * $opArr array: option data array
     * $isTextValue  boolean: put $opArr key or value in option value, true is key
     * $opValue string: selected value
     * $change string: select javascript event or others
     * 
     * return  checkbox element
     */

    public static function checkboxList($id, $opArr, $isTextValue, $opValue, $change = '') {

        $i = 0;$select='';
        foreach ($opArr as $key => $value) {
            $i++;
            $checked = !empty($opValue) && strpos($opValue, $key) > -1 ? 'checked="checked"' : '';
            $select .= '<label><input type="checkbox" name="' . $id . '"  value="' . ($isTextValue ? $key : ($i)) . '" ' . $change . ' ' . $checked . ' /><span>' . $value . '</span></label>';
        }
        return $select;
    }

    /*
     * put id and one colume to array from data result
     * 
     * $result array : database result
     * $name string: array value
     * 
     * return array
     */

    public static function getArray($result, $name) {
        $data = array();
        foreach ($result as $rows) {
            $data[$rows["id"]] = $rows[$name];
        }
        return $data;
    }

    public static function arrayToString($array) {
        $data = '';
        foreach ($array as $key => $value) {
            $data.=$key . '=' . $value . ' ,';
        }
        return $data;
    }

    public static function getAddressArray($result, $name) {
        $data = array();
        foreach ($result as $key => $value) {

            $data[$value["code"]] = $value[$name];
        }
        return $data;
    }

    public static function getArrayStatus($result, $name) {
        $data = array();
        foreach ($result as $rows) {
            $data[$rows["id"]] = $rows[$name] . ('<i>' . ($rows["status"] == 0 ? "%{OFFLINE}%" : "") . "</i>");
        }
        return $data;
    }

    /*
     * getOrderNo
     * 
     * $orderno string : order no value
     * $len string : the length of order no
     * $first_word string : first word of order no
     * 
     * return orderno
     */

    public static function getOrderNo($orderno, $len, $first_word) {
        $temp = "aa00000000000000000000000";
        $orderno = $temp . $orderno;
        $_length = strlen($orderno);
        $len = strlen($first_word) > 0 ? $len - strlen($first_word) : $len;
        return $first_word . substr($orderno, $_length - $len, $_length);
    }

    /*
     * diff date and now
     * 
     * $date string : date value
     * 
     * return days
     */

    public static function getDays($date) {

        return abs(ceil((strtotime($date) - strtotime("now")) / 86400));
    }

    /*
     * check file is exit
     * 
     * $path string : url root path
     * $file string : file name
     * 
     * return boolen
     */

    public static function checkFileIsExit($path, $file) {
        $serverFilePath = $_SERVER["SCRIPT_FILENAME"];
        $doc_dir = strpos($serverFilePath, $path);
        $doc_dir = substr($serverFilePath, 0, $doc_dir);

        if (!empty($file) && file_exists($doc_dir . $file)) {
            return 1;
        } else {
            return 0;
        }
    }

    /*
     * go previous page
     * 
     * $txt string : warn word
     * 
     *  
     */

    public static function GoToPrev($txt = '') {

        echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		       <script type="text/javascript">';
        if ($txt) {
            echo 'alert("' . $txt . '");';
        }
        echo 'history.back();';
        echo '</script>';
    }

    /*
     * warn window and go next page
     * 
     * $url string : url for next page
     * $txt string : warn word
     *  
     */

    public static function AlertTxt($url = '', $txt = '') {

        echo ' 
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
             
		  <script type="text/javascript">';
        if ($txt)
            echo 'alert("' . $txt . '");';
        if ($url)
            echo 'window.location.href=("' . $url . '");';
        echo '</script>';
    }

    public static function AlertTxtReload( $txt = '') {

        echo ' 
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
             
		  <script type="text/javascript">';
        if ($txt)
            echo 'alert("' . $txt . '");';

            echo 'window.location.reload();';
        echo '</script>';
    }

    public static function CouponAlertTxt($url = '', $txt = '', $btn='') {
        $btn=strlen($btn)==0?'确 定':$btn;
        echo '<html>
           <head>
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
            </head>
            <body> 
		  <script type="text/javascript">
		  window.alert = function(str)
                {
                    var shield = document.createElement("DIV");
                    shield.id = "shield";
                    shield.style.position = "absolute";
                    shield.style.left = "0px";
                    shield.style.top = "0px";
                    shield.style.width = "100%";
                    shield.style.height = document.body.scrollHeight+"px";
                    //弹出对话框时的背景颜色
                    shield.style.background = "#000";
                    shield.style.textAlign = "center";
                    shield.style.zIndex = "25";
                    shield.style.opacity = "0.7";
                    //背景透明 IE有效
                    //shield.style.filter = "alpha(opacity=0)";
                    var alertFram = document.createElement("DIV");
                    alertFram.id="alertFram";
                    alertFram.style.position = "absolute";
                    alertFram.style.left = "10%";
                    alertFram.style.top = "20%";
                    //alertFram.style.marginLeft = "-225px";
                    //alertFram.style.marginTop = "-75px";
                    alertFram.style.width = "80%";                    
                    alertFram.style.textAlign = "center";
                    alertFram.style.lineHeight = "150px";
                    alertFram.style.zIndex = "300";
                    strHtml = "<ul style=\"list-style:none;margin:0px;padding:0px;width:100%\">\n";
                    //strHtml += " <li style=\"background:#DD828D;text-align:left;padding-left:20px;font-size:14px;font-weight:bold;height:25px;line-height:25px;border:1px solid #F9CADE;\">[自定义提示]</li>\n";
                    strHtml += " <li style=\"border-radius: 8px 8px 0 0;background:#fff;text-align:left;font-size:18px;line-height:30px;padding: 20px 20px 10px 20px;border-left:1px solid #F9CADE;border-right:1px solid #F9CADE;word-wrap: break-word;\">"+str+"</li>\n";
                    strHtml += " <li style=\"border-radius: 0 0 8px 8px;background:#8874b3;text-align:center;font-weight:bold;height:35px;line-height:35px; border:1px solid #F9CADE;\"><div  onclick=\"doOk()\" style=\'font-size: 18px;width: 100%;color:#fff;\'>'.$btn.'</div></li>\n";
                    strHtml += "</ul>\n";
                    alertFram.innerHTML = strHtml;
                    document.body.appendChild(alertFram);
                    document.body.appendChild(shield);
                   // var ad = setInterval("doAlpha()",5);
                    this.doOk = function(){
                        alertFram.style.display = "none";
                        shield.style.display = "none";
                        window.location.href=("' . $url . '");
                    }
                    alertFram.focus();
                    document.body.onselectstart = function(){return false;};
                }
		  ';

        if ($txt)
            echo 'alert("' . $txt . '");';

        echo '</script>
         </body>
          </html>';
    }

    public static function showError($txt) {
        $html = '<div class="alert-box">'
                . '<div class="alert alert-danger alert-dismissable">'
                . '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'
                . '' . $txt . '</div></div>';
        echo $html;
    }

    public static function winOpen($url = '') {

        echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		  <script type="text/javascript">';
        if ($url)
            echo 'window.open("' . $url . '");';
        echo '</script>';
    }

    public static function getTotalPage($total_num, $number_page) {
        $number_page = empty($number_page) ? 10 : $number_page;
        $total_num = ceil($total_num / $number_page);
        return $total_num;
    }

    public static function getPages($goto, $item, $currp, $totalPage) {

        $totalPage = Tools::getTotalPage($totalPage, $item);

        $item = 10;
        $currp = $currp < 1 ? 1 : $currp;
        $goto = substr($goto, (strpos($goto, 'admin')), strlen($goto));
        if (strpos($goto, '&page') > 0)
            $goto = substr($goto, 0, strpos($goto, '&page'));
        $link_pageprev = $goto . '&page=' . ( ($currp == 1) ? (1) : ($currp - 1) ) . ' ';
        $link_pagenext = $goto . '&page=' . ( ($currp == $totalPage) ? ($totalPage) : ($currp + 1) ) . ' ';
        $link_pagehead = $goto . '&page=1  ';
        $link_pagelast = $goto . '&page=' . $totalPage . ' ';

        $prev = $currp % $item == 0 ? ((floor($currp / $item) - 1) * $item ) + 1 : (floor($currp / $item) * $item ) + 1;
        $next = $currp % $item == 0 ? floor($currp / $item) * $item : ((floor($currp / $item) + 1) * $item );
        $pageprev10 = $goto . '&page=' . ($prev - 1);
        $pagepnext10 = $goto . '&page=' . ($next + 1 );
        $next = $next > $totalPage ? $totalPage : $next;

        $link_pagelist = '';
        for ($i = $prev; $i <= $next; $i++) {
            $link_pagelist.= $currp == $i ? '<li class="current">' . $i . '</li>' : '<li><a href="' . $goto . '&page=' . $i . '">' . $i . '</a> </li>';
        }

        $data = '
          <div class="pagination scott">
            <ul>
  	      ';

        $data.=($currp > $item ) ? '<li class="disabled"><a href="' . $link_pagehead . '">第一頁</a></li>' : '';
        $data.=($prev > $item ) ? '<li class="disabled"><a href="' . $pageprev10 . '">上' . $item . '頁</a></li>' : '';
        $data.= $link_pagelist;
        $data.=( $totalPage > $next ) ? '<li><a href="' . $pagepnext10 . '">下' . $item . '頁</a></li>' : '';
        $data.=($totalPage > $next) ? '<li><a href="' . $link_pagelast . '">最後一頁</a></li>' : '';
        $data.=' 
             </ul>
           </div>
		   		
	     ';


        $data = $totalPage > 1 ? $data : '';
        return $data;
    }

    public static function getPagesPost($goto, $item, $currp, $totalPage) {
        $totalPage = Tools::getTotalPage($totalPage, $item);

        $currp = $currp < 1 ? 1 : $currp;
        //$goto = substr($goto, (strpos($goto, 'admin')), strlen($goto));
        if (strpos($goto, '&page') > 0)
            $goto = substr($goto, 0, strpos($goto, '&page'));

        $link_pageprev = 'javascript:setPageSubmit(' . ( ($currp == 1) ? (1) : ($currp - 1) ) . ') ';
        $link_pagenext = 'javascript:setPageSubmit(' . ( ($currp == $totalPage) ? ($totalPage) : ($currp + 1) ) . ') ';
        $link_pagehead = 'javascript:setPageSubmit(1)  ';
        $link_pagelast = 'javascript:setPageSubmit(' . $totalPage . ') ';

        $prev = $currp % $item == 0 ? ((floor($currp / $item) - 1) * $item ) + 1 : (floor($currp / $item) * $item ) + 1;
        $next = $currp % $item == 0 ? floor($currp / $item) * $item : ((floor($currp / $item) + 1) * $item );
        $pageprev10 = 'javascript:setPageSubmit( ' . ($prev - 1) . ' )  ';
        $pagepnext10 = 'javascript:setPageSubmit( ' . ($next + 1 ) . ' )  ';
        $next = $next > $totalPage ? $totalPage : $next;

        $link_pagelist = '';
        for ($i = $prev; $i <= $next; $i++) {
            $link_pagelist.= $currp == $i ? '<li class="paginate_button active"><a>' . $i . '</a></li>' : '<li><a href="javascript:setPageSubmit(' . $i . ')">' . $i . '</a> </li>';
        }

        $data = '
          <div class="dataTables_paginate pull-right">
            <ul class="pagination">
  	      ';
        $data.=($currp > $item ) ? '<li class="paginate_button"><a href="' . $link_pagehead . '">第一頁</a></li>' : '';
        $data.=($prev > $item ) ? '<li class="paginate_button"><a href="' . $pageprev10 . '">上' . $item . '頁</a></li>' : '';
        $data.= $link_pagelist;
        $data.=( $totalPage > $next ) ? '<li class="paginate_button"><a href="' . $pagepnext10 . '">下' . $item . '頁</a></li>' : '';
        $data.=($totalPage > $next) ? '<li class="paginate_button"><a href="' . $link_pagelast . '">最後一頁</a></li>' : '';
        $data.=' 
             </ul>
           </div>
	     ';

        $data = $totalPage > 1 ? $data : '';
        $data.=' <input type="hidden" id="page" name="page" />';
        //$data.=' <input type="hidden" id="page" name="page" /> <input type="hidden" id="func" name="func" /><input type="hidden" id="status" name="status" /><input type="hidden" id="id" name="id" />';
        return $data;
    }

    public static function getPagesPost2($goto, $item, $currp, $totalPage) {
        $totalPage = Tools::getTotalPage($totalPage, $item);

        $currp = $currp < 1 ? 1 : $currp;
        $goto = substr($goto, (strpos($goto, 'admin')), strlen($goto));
        if (strpos($goto, '&page') > 0)
            $goto = substr($goto, 0, strpos($goto, '&page'));

        $link_pageprev = 'javascript:setPageSubmit(' . ( ($currp == 1) ? (1) : ($currp - 1) ) . ') ';
        $link_pagenext = 'javascript:setPageSubmit(' . ( ($currp == $totalPage) ? ($totalPage) : ($currp + 1) ) . ') ';
        $link_pagehead = 'javascript:setPageSubmit(1)  ';
        $link_pagelast = 'javascript:setPageSubmit(' . $totalPage . ') ';

        $prev = $currp % $item == 0 ? ((floor($currp / $item) - 1) * $item ) + 1 : (floor($currp / $item) * $item ) + 1;
        $next = $currp % $item == 0 ? floor($currp / $item) * $item : ((floor($currp / $item) + 1) * $item );
        $pageprev10 = 'javascript:setPageSubmit( ' . ($prev - 1) . ' )  ';
        $pagepnext10 = 'javascript:setPageSubmit( ' . ($next + 1 ) . ' )  ';
        $next = $next > $totalPage ? $totalPage : $next;

        $link_pagelist = '';
        for ($i = $prev; $i <= $next; $i++) {
            $link_pagelist.= $currp == $i ? '<li class="current">' . $i . '</li>' : '<li><a href="javascript:setPageSubmit(' . $i . ')">' . $i . '</a> </li>';
        }

        $data = '
          <div class="pagination scott">
            <ul>
  	      ';

        $data.=($currp > $item ) ? '<li class="disabled"><a href="' . $link_pagehead . '">第一頁</a></li>' : '';
        $data.=($prev > $item ) ? '<li class="disabled"><a href="' . $pageprev10 . '">上' . $item . '頁</a></li>' : '';
        $data.= $link_pagelist;
        $data.=( $totalPage > $next ) ? '<li><a href="' . $pagepnext10 . '">下' . $item . '頁</a></li>' : '';
        $data.=($totalPage > $next) ? '<li><a href="' . $link_pagelast . '">最後一頁</a></li>' : '';
        $data.=' 
             </ul>
           </div>
		   		
	     ';

        $data = $totalPage > 1 ? $data : '';
//$data.=' <input type="hidden" id="page" name="page" /> <input type="hidden" id="func" name="func" /><input type="hidden" id="status" name="status" /><input type="hidden" id="id" name="id" />';
        return $data;
    }

    public static function getPagesPost_Index($goto, $item, $currp, $totalPage) {
        $totalPage = Tools::getTotalPage($totalPage, $item);

        $currp = $currp < 1 ? 1 : $currp;
        $goto = substr($goto, (strpos($goto, 'admin')), strlen($goto));
        if (strpos($goto, '&page') > 0)
            $goto = substr($goto, 0, strpos($goto, '&page'));

        $link_pageprev = 'javascript:setPageSubmit(' . ( ($currp == 1) ? (1) : ($currp - 1) ) . ') ';
        $link_pagenext = 'javascript:setPageSubmit(' . ( ($currp == $totalPage) ? ($totalPage) : ($currp + 1) ) . ') ';
        $link_pagehead = 'javascript:setPageSubmit(1)  ';
        $link_pagelast = 'javascript:setPageSubmit(' . $totalPage . ') ';

        $prev = $currp % $item == 0 ? ((floor($currp / $item) - 1) * $item ) + 1 : (floor($currp / $item) * $item ) + 1;
        $next = $currp % $item == 0 ? floor($currp / $item) * $item : ((floor($currp / $item) + 1) * $item );
        $pageprev10 = 'javascript:setPageSubmit( ' . ($prev - 1) . ' )  ';
        $pagepnext10 = 'javascript:setPageSubmit( ' . ($next + 1 ) . ' )  ';
        $next = $next > $totalPage ? $totalPage : $next;

        $link_pagelist = '';
        for ($i = $prev; $i <= $next; $i++) {
            $link_pagelist.= $currp == $i ? '<span class="current">' . $i . '</span>' : '<a href="javascript:setPageSubmit(' . $i . ')">' . $i . '</a>';
        }

        $data = '
          <div class="manu">            
  	      ';

        $data.=($currp > $item ) ? '<span class="disabled"><a href="' . $link_pagehead . '">第一頁</a></span>' : '';
        $data.=($prev > $item ) ? '<span class="disabled"><a href="' . $pageprev10 . '">上' . $item . '頁</a></span>' : '';
        $data.= $link_pagelist;
        $data.=( $totalPage > $next ) ? '<a href="' . $pagepnext10 . '">下' . $item . '頁</a>' : '';
        $data.=($totalPage > $next) ? '<a href="' . $link_pagelast . '">最後一頁</a>' : '';
        $data.=' 
           </div>
		   		
	     ';

        $data = $totalPage > 1 ? $data : '';
//$data.=' <input type="hidden" id="page" name="page" /> <input type="hidden" id="func" name="func" /><input type="hidden" id="status" name="status" /><input type="hidden" id="id" name="id" />';
        return $data;
    }

    public static function getPagesPostAjax($goto, $item, $currp, $totalPage, $pid) {
        $totalPage = Tools::getTotalPage($totalPage, $item);

        $currp = $currp < 1 ? 1 : $currp;
        $goto = substr($goto, (strpos($goto, 'admin')), strlen($goto));
        if (strpos($goto, '&page') > 0)
            $goto = substr($goto, 0, strpos($goto, '&page'));
// getcomment(find_id,page )  
        $link_pageprev = 'javascript:getcomment(' . $pid . ',' . ( ($currp == 1) ? (1) : ($currp - 1) ) . ' )';
        $link_pagenext = 'javascript:getcomment(' . $pid . ',' . ( ($currp == $totalPage) ? ($totalPage) : ($currp + 1) ) . ' )';
        $link_pagehead = 'javascript:getcomment(' . $pid . ',1)';
        $link_pagelast = 'javascript:getcomment(' . $pid . ',' . $totalPage . ') ';


        $prev = $currp % $item == 0 ? ((floor($currp / $item) - 1) * $item ) + 1 : (floor($currp / $item) * $item ) + 1;
        $next = $currp % $item == 0 ? floor($currp / $item) * $item : ((floor($currp / $item) + 1) * $item );
        $pageprev10 = 'javascript:getcomment(' . $pid . ',' . ($prev - 1) . ' )  ';
        $pagepnext10 = 'javascript:getcomment(' . $pid . ',' . ($next + 1 ) . ' )  ';
        $next = $next > $totalPage ? $totalPage : $next;

        $link_pagelist = '';
        for ($i = $prev; $i <= $next; $i++) {
            $link_pagelist.= $currp == $i ? '<li class="current">' . $i . '</li>' : '<li><a href="javascript:getcomment(' . $pid . ',' . $i . ')">' . $i . '</a> </li>';
        }

        $data = '
          <div class="pagination scott">
            <ul>
  	      ';

        $data.=($currp > $item ) ? '<li class="disabled"><a href="' . $link_pagehead . '">第一頁</a></li>' : '';
        $data.=($prev > $item ) ? '<li class="disabled"><a href="' . $pageprev10 . '">上' . $item . '頁</a></li>' : '';
        $data.= $link_pagelist;
        $data.=( $totalPage > $next ) ? '<li><a href="' . $pagepnext10 . '">下' . $item . '頁</a></li>' : '';
        $data.=($totalPage > $next) ? '<li><a href="' . $link_pagelast . '">最後一頁</a></li>' : '';
        $data.=' 
             </ul>
           </div>
		   		
	     ';

        $data = $totalPage > 1 ? $data : '';
//$data.=' <input type="hidden" id="page" name="page" /> <input type="hidden" id="func" name="func" /><input type="hidden" id="status" name="status" /><input type="hidden" id="id" name="id" />';
        return $data;
    }

    function utf8Urldecode($value) {
        if (is_array($value)) {
            foreach ($value as $key => $val) {
                $value[$key] = utf8Urldecode($val);
            }
        } else {
            $value = preg_replace('/%([0-9a-f]{2})/ie', 'chr(hexdec("$1"))', (string) $value);
        }
        return $value;
    }

    public static function std_class_object_to_array($stdclassobject) {
        $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
        foreach ($_array as $key => $value) {
            $value = (is_array($value) || is_object($value)) ? Tools::std_class_object_to_array($value) : $value;
            $array[$key] = $value;
        }

        return $array;
    }

    public static function removerQueryString($url, $key) {

        return substr($url, 0, (strpos($url, $key) == 0 ? strlen($url) : strpos($url, $key) - 1));
    }

    public static function addQueryString($url, $key, $value) {
        return $url . (!empty($value) ? '&' . $key . '=' . $value : "");
    }

    public static function sendMail($info, $to) {
        header("content-type:text/html;charset=utf-8");
        ini_set("magic_quotes_runtime", 0);
        include_once ('plugin/phpmailer/class.phpmailer.php');
        include_once ('plugin/phpmailer/class.smtp.php');
        include_once ('plugin/phpmailer/class.pop3.php');

        $log = new Logging();
        $log->lfile('mail');

        $Config = Config::getInstance();
        $SMTP_arr = $Config->getSMTP();
        $error = 0;
        try {
            $mail = new PHPMailer(true);
            $mail->IsSMTP();
            $mail->CharSet = 'UTF-8'; //设置邮件的字符编码，这很重要，不然中文乱码
            $mail->SMTPAuth = true;                  //开启认证
            //$mail->SMTPSecure = "ssl"; 
            $mail->Port = $SMTP_arr["Port"];
            $mail->Host = $SMTP_arr["Host"];
            $mail->Username = $SMTP_arr["Username"];
            $mail->Password = $SMTP_arr["Password"];
            $mail->AddReplyTo($SMTP_arr["Username"], "mckee"); //回复地址
            $mail->From = $SMTP_arr["Username"];
            $mail->FromName = $SMTP_arr["sender_name"];

            $log->lwrite('host:' . $mail->Host . ", user:" . $mail->Username . ', pwd:' . $mail->Password);
            foreach ($to as $val) {
                $mail->AddAddress($val);
                $log->lwrite($val);
            }
            //$mail->Subject  = $title1;//不能被赋予变量，会报错SMTP Error: Data not accepted.
            $mail->Subject = "寻店系统修改";
            $mail->Body = $info;
            $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; //当邮件不支持html时备用显示，可以省略
            $mail->WordWrap = 80; // 设置每行字符串的长度 

            $mail->IsHTML(true);
            $mail->Send();
            //echo '邮件已发送';
        } catch (phpmailerException $e) {
            //echo "邮件发送失败：".$e->errorMessage();
            $error = $e->errorMessage();
            $log->lwrite('error:' . $error);
            $log->lwrite('....................................');
        }
    }

    public static function transcoding($datas) {
        if (is_array($datas) && count($datas) > 0) {
            foreach ($datas as $k => $v) {
                if (is_array($v) && count($v) > 0) {
                    $datas[$k] = Tools::transcoding($v);
                } else {
                    $text = urlencode($v);
                    $text = iconv("GB2312", "UTF-8", $text);
                    $datas[$k] = $text;
                }
            }
        }
        return $datas;
    }

    public static function transcodingObject($stdclassobject) {
        $array = array();
        $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
        foreach ($_array as $key => $value) {
            $value = (is_array($value) || is_object($value)) ? Tools::transcodingObject($value) : $value;

            $text = urlencode($value);
            $text = iconv("GB2312", "UTF-8", $text);
            $array[$key] = $text;
        }

        return $array;
    }

    public static function getIP() {
        $ip = '';
        $unknown = 'unknown';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
          处理多层代理的情况或者使用正则方式：$ip = preg_match("/[d.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
         */
        if (false !== strpos($ip, ',')) {
            $ip = reset(explode(',', $ip));
        }
        //$ip = $_SERVER['REMOTE_ADDR']; 
        return $ip;
    }

    public static function getName($name) {
        $rname = "";
        $findme = '店';
        $pos = mb_strpos($name, $findme);
        if ($pos === false) {
            $rname = $name;
        } else {
            $rname .= mb_substr($name, 0, $pos);
            $rname .=$findme;
        }
        return $rname;
    }

    public static function getProductCate($cate_list, $cate) {
        $cate = explode(",", $cate);
        $_temp = array();
        foreach ($cate as $k => $v) {
            $_temp[$v] = $cate_list[$v];
        }
        return $_temp;
    }

    public static function getQRCode($text, $image, $size=6) {
        require_once 'plugin/phpqrcode/phpqrcode.php';

        $errorCorrectionLevel = 'L'; //容错级别 L（QR_ECLEVEL_L，7%），M（QR_ECLEVEL_M，15%），Q（QR_ECLEVEL_Q，25%），H（QR_ECLEVEL_H，30%）
        $matrixPointSize = $size; //生成图片大小
        //生成二维码图片 
       return QRcode::png($text, $image, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    public static function getQRCodeLogo($text, $image, $logo) {
        require_once 'plugin/phpqrcode/phpqrcode.php';

        $errorCorrectionLevel = 'L'; //容错级别 L（QR_ECLEVEL_L，7%），M（QR_ECLEVEL_M，15%），Q（QR_ECLEVEL_Q，25%），H（QR_ECLEVEL_H，30%）
        $matrixPointSize = 6; //生成图片大小 
        //生成二维码图片 
        QRcode::png($text, $image, $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = imagecreatefromstring(file_get_contents($image));
        if ($logo !== FALSE) {

            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR); //二维码图片宽度 
            $QR_height = imagesy($QR); //二维码图片高度  
            $logo_width = imagesx($logo); //logo图片宽度 
            $logo_height = imagesy($logo); //logo图片高度  
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小 
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        }

        //输出图片 
        //Header("Content-type: image/png");
        ImagePng($QR, $image);
    }
    
    public static function getProductImg($image) {
        $img = "";
        if(is_array($image)&&count($image)>0){
            $img = reset($image);
        }
        return $img;
    }

    //加密函数
    public static function lock_url($txt,$key='gansoshjieta168'){
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $nh = rand(0,64);
        $ch = $chars[$nh];
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
            $tmp .= $chars[$j];
        }
        return urlencode($ch.$tmp);
    }
//解密函数
    public static function unlock_url($txt,$key='gansoshjieta168'){
        $txt = urldecode($txt);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $ch = $txt[0];
        $nh = strpos($chars,$ch);
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = substr($txt,1);
        $tmp = '';
        $i=0;$j=0; $k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
            while ($j<0) $j+=64;
            $tmp .= $chars[$j];
        }
        return base64_decode($tmp);
    }

    public static function sortBy(&$items, $key, $descending = false){
        if (is_array($items)){
            return usort($items, function($a, $b) use ($key, $descending){
                $cmp = strCmp($a[$key], $b[$key]);
                return $descending? -$cmp : $cmp;
            });
        }
        return false;
    }
    
    //判断单个商品是否存在优惠
    public static function checkProductPromotion($product, $promotion){
        $result = array("id"=>0,"disitem"=>'');
        if(!empty($product)&&!empty($promotion)){
            if($promotion['product_type']==0){//全店
                $result = $promotion;
            }
            if($promotion['product_type']==1){//手动选择
                if(strpos($promotion['productID'], "'".$product['id']."'")!==false){//id存在促销商品id中
                    $result = $promotion;
                }
                $cate_key = Data::$_platform[$_SESSION["wx_user"]["platform_id"]]['cate'];
                //var_dump($cate_key);
                if(empty($cate_key)){
                    $result = $promotion;//平台无法确认（ismobile、isweixin）
                }
                $cate_arr = empty($product[$cate_key])?array():explode(",", $product[$cate_key]);
                //var_dump($cate_arr);
                foreach ($cate_arr as $k => $val) {//判断商品分类中是否有分类在促销分类中
                    if(strpos($promotion['cateID'], $val)!==false){
                        $result = $promotion;
                        break;
                    }
                }
            }
        }
        
        if($result['id']>0){
            $result['disitem'] = $promotion['promotion_type']==0?"<s>减</s>满".$promotion['price']."减".$promotion['dis_price']."元":"<s>赠</s>满".$promotion['price']."赠送".$promotion['promotion_name'];
        }
        return $result;
    }
    


    public static function aletMSG($msg, $url1, $url2, $btn1, $btn2)
    {
        $btn_html=' <div class="bnt">
                        <a href="'.$url1.'" class="btn1">'.$btn1.'</a>
                        <a href="'.$url2.'" class="btn2">'.$btn2.'</a>
                    </div>';
        if (!empty($btn1) && empty($btn2)){
            $btn_html=' <div class="bnt">
                        <a href="'.$url1.'" class="only">'.$btn1.'</a> 
                    </div>';
        }

        $html=' 
            <div class="group_tc_bg">
                <div class="group_tc">
                    <p>'.$msg.'</p>
                    '.$btn_html.'
                </div>
            </div> 
        ';
        return $html;
    }


    public static function controllerAletMSG($msg, $url1, $url2, $btn1, $btn2)
    {
        $html='
        <html>
           <head>
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
           <style>
            .group_tc_bg{ width:100%; height:100%; position:fixed; left:0px; top:0px; background:rgba(0, 0, 0, 0.7);}
            .group_tc{ width:260px; margin:30% auto 0; text-align:center; background:#fff; border-radius:4px; -moz-border-radius:4px;}
            .group_tc p{ padding:22px 20px; font-size:16px; line-height:24px; margin:0px;}
            .group_tc .bnt{ line-height:45px; border-top:1px solid #ddd; overflow:hidden;}
            .group_tc .bnt a{ width:50%; display:block; float:left; font-size:14px; text-decoration:none; color:#333;}
            .group_tc .bnt a:last-child{ width:-moz-calc(50% - 1px); width:-webkit-calc(50% - 1px); width:calc(50% - 1px); color:#dd0050; border-left:1px solid #ddd;} </style>
             </head>
            <body>
            <div class="group_tc_bg">
                <div class="group_tc">
                    <p>'.$msg.'</p>
                    <div class="bnt">
                        <a href="'.$url1.'" class="btn1">'.$btn1.'</a>
                        <a href="'.$url2.'" class="btn2">'.$btn2.'</a>
                    </div>
                </div>
            </div>
            </body>
          </html>
        ';
        return $html;
    }


    public static function tempOrderIdCookie(){
        $temp_orderid=$_COOKIE['toid'];
        $pattern = "/\d+/";
        preg_match($pattern, $temp_orderid, $matches);
        if (!empty($matches) && count($matches)>0){
            return $matches[0];
        }
        return 0;
    }



    public static function getPartnerMemberCode($memberid){

        $hashids = Hashids::instance(13, 'GansoShjietaPartner');
        $encode_id = $hashids->encode($memberid); //加密

        return $encode_id;
    }

    public static function getPartnerMemberId($code){
        $hashids = Hashids::instance(13, 'GansoShjietaPartner');
        $member_id = $hashids->decode($code);

        return $member_id;
    }

    public static function cleanHTMLTag($val){
        foreach($val as $t=>$tt){
            if (!empty($tt) && !is_array($tt)) {
                $val[$t] = htmlspecialchars($tt);
            }else if (is_array($tt)){
                $val[$t]=Tools::cleanHTMLTag($tt);
            }
        }

        return $val;
    }

    public static function partnerQRCode($partner_id, $activity_id){


        $uid = time();
        //header("Content-type: image/png");
//二維碼
        $dst = "webroot/file/partner_qrcode/" . $activity_id . "_" . $partner_id . "_qrcode.png";
        $dst_im =imagecreatefrompng($dst);

        if ($dst_im === false) {
            return;
        }
        $dst_path = "webroot/file/temp/".$activity_id . "_" . $partner_id  . '_qrcode.png';
        imagepng($dst_im, $dst_path); //另存成png檔案
        $dst_info = getimagesize($dst_path);

//要合成的底圖
        $src ="webroot/partner/images/partner_qrcode.png"; //預設
//合成底圖的資訊
        $src_im = imagecreatefrompng($src);
        if ($src_im === false) {
            return;
        }
        $src_info = getimagesize($src);

        $dst_w=$src_info[0];
        $dst_h=$src_info[1];

//縮圖到印製的大小
        $resize_dst = Tools::resizeImage($dst_path, $dst_w, $dst_h);
        $resize_dst_path = "webroot/file/temp/".$uid . '_resize_dst.png';
        imagepng($resize_dst, $resize_dst_path); //另存成png檔案
        $resize_dst_info = getimagesize($resize_dst_path);

//建立新的一張空白圖
        $show = imagecreatetruecolor($src_info[0], $src_info[1]);
//先複製來源圖到新圖層的左邊
        imagecopy($show, $src_im, 0, 0, 0, 0, $src_info[0], $src_info[1]);
        imagecopy($show, $dst_im, 125, 235, 0, 0, $dst_info[0], $dst_info[1]);

//输出合成圖（直接顯示的做法）
        //imagepng($show);
//或輸出合成圖至檔案
        imagepng($show,   "webroot/file/partner_qrcode/" . $activity_id . "_" . $partner_id  . ".png");
//釋放檔案描述子
        imagedestroy($resize_dst);
        imagedestroy($src_im);
        imagedestroy($show);
//移除暫存檔
        unlink($dst_path);
        //unlink($src_path);
        unlink($resize_dst_path);

    }


    public static function resizeImage($filename, $max_width, $max_height) {
        list($orig_width, $orig_height) = getimagesize($filename);
        $width = $orig_width;
        $height = $orig_height;
        //原圖比設定縮圖高還高
        if ($height > $max_height) {
            //先依照比例縮放寬
            $width = ($max_height / $height) * $width;
            //指定高為縮圖高
            $height = $max_height;
        }
        //如果目前的寬還是比設定縮圖寬還寬
        if ($width > $max_width) {
            //把高也依照比例再縮放
            $height = ($max_width / $width) * $height;
            //指定寬為縮圖寬
            $width = $max_width;
        }
        //建立空白畫布
        $image_p = imagecreatetruecolor($width, $height);
        //把圖片載入
        $image = imagecreatefrompng($filename);
        //複製並重新取樣
        imagecopyresampled($image_p, $image, 0, 0, 0, 0,
            $width, $height, $orig_width, $orig_height);
        //清除檔案描述子
        imagedestroy($image);
        return $image_p;
    }


    public static function clearSymbolForCSV($data){
        $data=preg_replace("/(\n)|(\r)|(\t)|(,)|(，)( )/", '!', $data);
        return $data;
    }

    public static function userTextEncode($str){
        if(!is_string($str))return $str;
        if(!$str || $str=='undefined')return '';

        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
            return addslashes($str[0]);
        },$text); //將emoji的unicode留下，其他不動，這裡的正則比原答案增加了d，因為我發現我很多emoji實際上是\ud開頭的，反而暫時沒發現有\ue開頭。
        return json_decode($text);
    }

    /**
    解碼上面的轉義
     */
    public static function userTextDecode($str){
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i',function($str){
            return '\\';
        },$text); //將兩條斜槓變成一條，其他不動
        return json_decode($text);
    }
}

?>